// TODO: CODE REVIEW & CLEANUP!
//
// DevicesScreen.xaml.cs
//

using System.Text;
using System.Windows;
using System.Windows.Controls;
using HomeUX.ClientControlSupport;
using HomeUX.Synchronization;

namespace HomeUX.ClientAppSupport
{

public partial class DevicesScreen : UserControl
{
    Screen _screen;
    SyncNode _allDevicesNode;

    public DevicesScreen()
    {
        InitializeComponent();
        Loaded += DevicesScreen_Loaded;
    }

    void DevicesScreen_Loaded(object sender, RoutedEventArgs e)
    {
        _screen = ClientFramework.Current.TryFindScreen(this);
        ISyncClient syncClient = ClientGlobals.GetSyncClient(this);
        _allDevicesNode = (SyncNode)syncClient.SyncTree.TryFindNode(SyncPath.FromString("DeviceStatus"));
        _screen.Opened += delegate
        {
            UpdateBusyDevicesTextBlock();
        };
        _allDevicesNode.DescendantChanged += delegate
        {
            if (_screen.IsOpen)
                UpdateBusyDevicesTextBlock();
        };
    }

    void UpdateBusyDevicesTextBlock()
    {
        StringBuilder text = new StringBuilder(200);
        foreach (SyncNodeBase deviceNode in _allDevicesNode.Children)
        {
            int busyCount = deviceNode.TryFindValue<int>("BusyCount", 0);
            if (busyCount > 0)
            {
                if (text.Length > 0)
                    text.Append("; ");
                text.AppendFormat("{0} ({1})", deviceNode.Name, busyCount);
            }
        }
        BusyDevicesTextBlock.Text = (text.Length == 0) ? "(None)" : text.ToString();
    }
}

}
